from flask import Flask, render_template, request, jsonify, session
from prometheus_service import PrometheusQueryService
from config import config
import os

# 初始化Flask应用
app = Flask(__name__)
app.config['SECRET_KEY'] = config.SECRET_KEY

# 初始化Prometheus查询服务
prometheus_service = PrometheusQueryService()

@app.route('/')
def index():
    """首页路由"""
    # 初始化历史记录
    if 'history' not in session:
        session['history'] = []
    
    return render_template('index.html', history=session['history'])

@app.route('/query', methods=['POST'])
def query():
    """处理查询请求"""
    try:
        # 获取请求数据
        data = request.json
        natural_language_query = data.get('query', '')
        time_range = data.get('time_range', '1h')
        graph_type = data.get('graph_type', config.DEFAULT_GRAPH_TYPE)
        
        if not natural_language_query:
            return jsonify({'success': False, 'error': '请输入查询语句'})
        
        # 执行查询
        result = prometheus_service.query_with_natural_language(
            natural_language_query,
            time_range,
            graph_type
        )
        
        # 如果查询成功，添加到历史记录
        if result['success']:
            history_item = {
                'query': natural_language_query,
                'promql': result['promql'],
                'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            }
            
            # 更新历史记录
            if 'history' not in session:
                session['history'] = []
            
            session['history'].insert(0, history_item)
            
            # 限制历史记录数量
            if len(session['history']) > config.MAX_HISTORY_ITEMS:
                session['history'] = session['history'][:config.MAX_HISTORY_ITEMS]
            
            session.modified = True
        
        return jsonify(result)
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)})

@app.route('/history', methods=['GET'])
def get_history():
    """获取历史记录"""
    history = session.get('history', [])
    return jsonify({'history': history})

@app.route('/history/<int:index>', methods=['POST'])
def reuse_history(index):
    """复用历史查询"""
    try:
        history = session.get('history', [])
        
        if 0 <= index < len(history):
            history_item = history[index]
            return jsonify({
                'success': True,
                'query': history_item['query'],
                'promql': history_item['promql']
            })
        else:
            return jsonify({'success': False, 'error': '历史记录不存在'})
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)})

@app.route('/templates', methods=['GET'])
def get_templates():
    """获取查询模板"""
    # 在实际应用中，这里可以从数据库或文件中加载模板
    templates = [
        {
            'name': 'API请求量',
            'query': '过去5分钟内api_server的请求量'
        },
        {
            'name': '错误率',
            'query': '过去1小时内每个服务的错误率'
        },
        {
            'name': 'CPU使用率',
            'query': '过去10分钟内每个节点的CPU使用率'
        },
        {
            'name': '内存使用率',
            'query': '过去10分钟内每个节点的内存使用率'
        }
    ]
    
    return jsonify({'templates': templates})

if __name__ == '__main__':
    app.run(debug=config.DEBUG, host='0.0.0.0', port=5000)
